require("../lib/jquery.actual.min.js");

/**
 *
 * @param {*} slide_wrapper 外部盒子
 * @param {*} slide_locked  是否已认证
 * @param {*} callback      回调函数
 */
function slider(slide_wrapper, slide_locked, callback) {
  var slideBox = $(slide_wrapper).find(".slide_box");
  var slideXbox = $(slide_wrapper).find(".slide_xbox");
  var btn = $(slide_wrapper).find(".btn")[0];
  var slideBoxWidth = slideBox.actual("outerWidth");
  var btnWidth = $(slide_wrapper).find(".btn").actual("outerWidth");
  var token = slide_locked.token;

  // reset start
  if (slide_locked.locked) {
    $(slide_wrapper).attr("slide", "");
    slideXbox.html('<div class="btn"></div>').width(btnWidth + "px");
    slide_locked.locked = false;
    btn = $(slide_wrapper).find(".btn")[0];
  }
  // reset end

  //移动端
  var cont = $(slide_wrapper).find(".btn");
  var startX = 0,
    sX = 0,
    moveX = 0,
    leftX = 0;
  cont.on({
    //绑定事件
    touchstart: function (e) {
      startX = e.originalEvent.targetTouches[0].pageX; //获取点击点的X坐标
      // sX = $(this).offset().left; //相对于当前窗口X轴的偏移量
      sX = 0;
      leftX = startX - sX; //鼠标所能移动的最左端是当前鼠标距div左边距的位置
    },
    touchmove: function (e) {
      e.preventDefault();
      moveX = e.originalEvent.targetTouches[0].pageX; //移动过程中X轴的坐标
      var objX = moveX - leftX + btnWidth;
      if (objX < btnWidth) {
        objX = btnWidth;
      }
      if (objX > slideBoxWidth) {
        objX = slideBoxWidth;
      }
      slideXbox.width(objX + "px");
    },
    touchend: function (e) {
      var objX = moveX - leftX + btnWidth;
      if (objX < slideBoxWidth) {
        objX = btnWidth;
        slideXbox.width(objX + "px");
      } else {
        objX = slideBoxWidth;
        slideXbox.html('验证中...<div class="btn loading"></div>');
        callback(setBtnStatus, slide_locked)
      }
    },
  });

  function setBtnStatus (res) {
    if (res) {
      slide_locked.locked = true;
      slideXbox.html('验证通过<div class="btn active"></div>');
    } else {
      // alert("验证失败");
      slideXbox.html('<div class="btn"></div>');
      slideXbox.width(btnWidth + "px");
      document.onmousemove = null;
      document.onmouseup = null;
      slider(slide_wrapper, slide_locked, callback)
      return;
    }
  }
}

module.exports = slider;
